<?php

namespace App\Admin\Controllers;

use App\Admin\Grid\NGrid;
use App\Admin\Tools\Finance\IncomeDeleteTool;
use App\Models\AdminUsersRelatedModel;
use App\Models\ContractedCustomerModel;
use App\Models\FinanceIncomeModel;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Form;
use Illuminate\Support\Facades\Auth;

class FinanceIncomeController extends AdminController
{
    protected $title = '财务收入';

    public function grid(): NGrid
    {
        $grid = new NGrid(new FinanceIncomeModel);
        $grid->model()
            ->leftJoin('contracted_customer', 'contracted_customer.id', 'finance_income.contracted_customer_id')
            ->leftJoin('admin_users', 'admin_users.id', 'finance_income.operate_id')
            ->orderByDesc('finance_income.created_at')
            ->select([
                'finance_income.*',
                'admin_users.name as operate_name',
                'contracted_customer.male_name as male_name',
                'contracted_customer.female_name as female_name',
                'contract_no',
                'contract_amount',
            ]);

        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('contracted_customer_id', '客户信息')->select((new ContractedCustomerModel)->customerSelect());
                $filter->between('income_date', __('finance_income.incomeDate'))->date();
                $filter->equal('finance_income-operate_id', '操作人')->select((new AdminUsersRelatedModel)->stuff());
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->like('income_type', '收款类型');
                $filter->like('finance_income-remark', __('l.remark'));
            });
        });
        if (!ISADMIN) {
            if (in_array(Auth::user()->roles->first()->slug, ['boss', 'finance'])) $grid->model()->where('finance_income.main_id', MAINID);
            else $grid->model()->where('finance_income.operate_id', USERID);
        }
//        if (!ISADMIN) {
//            if (ISMAIN) $grid->model()->where('finance_income.main_id', USERID);
//            else $grid->model()->where('finance_income.main_id', MAINID);
//        } else $grid->model()->where('finance_income.operate_id', USERID);

        $grid->header(function ($query) {
            $success = FinanceIncomeModel::query()->where('status', 1);
            if (!ISADMIN) {
                if (ISMAIN) $success->where('finance_income.main_id', USERID);
                else $success->where('finance_income.main_id', MAINID);
            } else $success->where('finance_income.operate_id', USERID);
            $success = $success->sum('actual_income_amount');

            $refuse = FinanceIncomeModel::query()->where('status', 0);
            if (!ISADMIN) {
                if (ISMAIN) $refuse->where('finance_income.main_id', USERID);
                else $refuse->where('finance_income.main_id', MAINID);
            } else $refuse->where('finance_income.operate_id', USERID);
            $refuse = $refuse->sum('actual_income_amount');

            return '已审核：' . $success . '（元）待审核：' . $refuse . '（元）';
        });
        if (Auth::user()->roles->first()->slug == 'Administrator') $grid->column('id', 'ID')->sortable();
        $grid->column('income_date', __('finance_income.incomeDate'));
        $grid->column('income_type', __('finance_income.incomeType'));
        $grid->column('customer_info', '客户信息')->display(function () {
            return $this->contract_no . '-'
                . $this->male_name . '-' . $this->female_name . '-' . $this->contract_amount;
        });
//        $grid->column('income_received', __('finance_income.incomeReceived'));
        $grid->column('income_amount', __('finance_income.incomeAmount'));
        $grid->column('actual_income_amount', __('finance_income.actualIncomeAmount'));
        $grid->column('remark', __('l.remark'));
        $grid->column('operate_name', '操作人');
        $grid->column('created_at', __('l.createdAt'))->display(function () {
            return date('Y-m-d H:i:s', strtotime($this->created_at));
        });
        $grid->column('status', __('l.status'))->display(function () {
            return $this->status === 0 ? '待审核' : __('l.auditStatusArr')[$this->status];
        });
        $grid->column('audit_remark', __('finance_income.auditRemark'));
        $grid->actions(function (Actions $action) {
            if ($action->row->status === 1) $action->disableEdit();
//            $action->disableEdit(false);
            $action->disableDelete();
            $action->disableView();
//            if ($action->row->status !== 1) $action->append(new IncomeDeleteTool($action->row->id));
        });
        $grid->disableActions(false);
        $grid->disableCreateButton();
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new FinanceIncomeModel);
        $form->hidden('id');
        $form->hidden('income_received');
        $form->hidden('operate_id');
        $form->hidden('main_id');
        $form->hidden('follow_user_id');
        $form->column(1 / 2, function (Form $form) {
            $form->text('income_type', __('finance_income.incomeType'));
            $form->select('contracted_customer_id', '客户名')->options((new ContractedCustomerModel)->customerSelect())->required();
            $form->currency('income_amount', __('finance_income.incomeAmount'))->symbol('￥');
            // 显示中文大写（只读）
            $form->text('income_amount_display', '金额大写')->placeholder('大写金额')->disable();

            Admin::script(<<<SCRIPT
                $("input[name='income_amount']").on('input', function(e) {
                    const amount = $(this).val();
                    $.ajax({
                        url: '/admin/ajax/numberToChinese', // 自定义接口路由
                        type: 'post',
                        data: {
                            amount: amount,
                            _token: $.admin.token
                        },
                        success: function(response) {
                        console.log(response);
                            $("#income_amount_display").val(response.data);
                        }
                    });
                });
            SCRIPT);
            $form->currency('actual_income_amount', __('finance_income.actualIncomeAmount'))->symbol('￥');
            // 显示中文大写（只读）
            $form->text('actual_income_amount_display', '金额大写')->placeholder('大写金额')->disable();

            Admin::script(<<<SCRIPT
                $("input[name='actual_income_amount']").on('input', function(e) {
                    const amount = $(this).val();
                    $.ajax({
                        url: '/admin/ajax/numberToChinese', // 自定义接口路由
                        type: 'post',
                        data: {
                            amount: amount,
                            _token: $.admin.token
                        },
                        success: function(response) {
                        console.log(response);
                            $("#actual_income_amount_display").val(response.data);
                        }
                    });
                });
            SCRIPT);

            $form->date('income_date', __('finance_income.incomeDate'))->format('YYYY-MM-DD')->default(date('Y-m-d'));
        });

        $form->column(1 / 2, function (Form $form) {
            $form->textarea('remark', __('l.remark'))->rows(10);
        });

        $form->saving(function (Form $form) {
            $contracted = ContractedCustomerModel::query()
                ->where('id', $form->contracted_customer_id)->first();
            $income = FinanceIncomeModel::query()
                ->where('contracted_customer_id',
                    $form->contracted_customer_id)
                ->orderByDesc('id')
                ->first();
            $form->income_received = is_null($income) ? $form->actual_income_amount : bcadd($form->actual_income_amount, $income->income_received, 2);
            $form->operate_id = auth()->user()->id;
            $form->follow_user_id = $contracted->operate_id;
            $form->main_id = MAINID;
        });
        return $form->confirm('确定提交吗');
    }
}
